package user

import (
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	UserModel "jy_go/app/admin/model/user"
	"jy_go/common"
	"jy_go/db"
	"jy_go/jy_log"
	"math"
	"strconv"
)


var (
	Db = db.GetDb()
)

//用户列表
func Lst(c *gin.Context){
	Limit, err := strconv.Atoi(c.DefaultPostForm("limit", "10"))

	if err != nil{
		c.JSON(400,gin.H{"code":"error","message":"错误传参"})
		return
	}

	Page,err := strconv.Atoi(c.DefaultPostForm("page", "1"))
	if err != nil{
		c.JSON(400,gin.H{"code":"error","message":"错误传参"})
		return
	}

	//初始化结构体
	var data = make([]UserModel.User, 0)
	var model UserModel.User
	var count int64
	dbtitle := Db.Model(&model)
	if err := dbtitle.Count(&count).Error;err != nil{
		if errors.Is(err,gorm.ErrRecordNotFound){
			c.JSON(200,gin.H{"code":"success","message":"暂无数据","data":data,"limit":Limit,"page":Page,"count":0})
			return
		}
		go jy_log.JyLog("查询失败，err：" + err.Error())
		c.JSON(400,gin.H{"code":"error","message":"查询失败"})
		return
	}
	dbtitle.Limit(Limit).Offset((Page - 1) * Limit).Find(&data)

	c.JSON(200,gin.H{"code":"success","message":"查询成功","data":data,"limit":Limit,"page":Page,"count":math.Ceil(float64(count) / float64(Limit))})
	return
}

func Upd(c *gin.Context)  {
	//接收数据
	var form UserModel.User

	if err := c.Bind(&form); err != nil {
		c.JSON(400,gin.H{"code":"success","message":"请填写要修改的内容"})
		return
	}

	//验证数据
	if err := common.Validate(&form); err != ""{
		c.JSON(400,gin.H{"code":"error","message":err})
		return
	}

	if err := Db.Where("id = ?",form.ID).Updates(&form).Error;err != nil {
		c.JSON(400,gin.H{"code":"error","message":"修改失败"})
		go jy_log.JyLog("修改失败，err：" + err.Error())
		return
	}
	c.JSON(200,gin.H{"code":"success","message":"修改成功"})
	return
}
















